package com.hongxun.budget.ui.activity.ys;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.BDataDictionaryEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.greendao.SysUserEntityDao;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.adapter.SpinnerAdapter;
import com.hongxun.budget.ui.dialog.LineNameDialog;
import com.hongxun.budget.ui.dialog.ListCheckDialog;
import com.hongxun.budget.ui.dialog.NoticeDialog;
import com.hongxun.budget.ui.dialog.WireDialog;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.DataUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.budget.utils.TestingUtils;
import com.hongxun.entity.LineName;
import com.hongxun.entity.LoginInfo;
import com.hongxun.greenentity.SysUserEntity;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.tk.BEstimateEntity;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.greenentity.tk.BProjectApplicationEntity;
import com.hongxun.greenentity.ys.EPBaseEntity;
import com.hongxun.greenentity.ys.EPRangeEntity;
import com.hongxun.greenentity.ys.EPWireEntity;
import com.hongxun.interfaces.ClickListener;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建项目
 */
public class CheckCreateActivity extends BaseActivity {

    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.right_save)
    Button rightSave;
    List<String> datas = new ArrayList<>();
    @BindView(R.id.list)
    RecyclerView listView;
    SuperAdapter<String> superAdapter;
    SpinnerAdapter<BDataDictionaryEntity> projectTypeSpinnerAdapter;//项目类型
    SpinnerAdapter<BDataDictionaryEntity> workTypeSpinnerAdapter;//改造类型
    @BindView(R.id.user)
    TextView user;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    List<SysUserEntity> userEntities = new ArrayList<>();//参与人员
    int id = R.id.radioButton3;
    DaoSession session;
    List<BMaterialEntity> materialEntities = new ArrayList<>();//导线
    List<LineName> lineNames = new ArrayList<>();//线路台区
    @BindView(R.id.project_name)
    EditText projectName;

    boolean update = false;//是否是修改

    EPBaseEntity apBaseEntity;//修改时的基础信息
    @BindView(R.id.is_draw)
    CheckBox isDraw;
    @BindView(R.id.radioButton2)
    RadioButton radioButton2;

    List<BDataDictionaryEntity> categoryTypes;
    List<BDataDictionaryEntity> projectType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_project_ys_create;
    }

    boolean init = false;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus && !init) {
            init = true;
            initDefultData();
        }
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        update = getIntent().getBooleanExtra("update", false);
        session = GreenDaoManager.getInstance().getmDaoSession();
        rightSave.setVisibility(View.VISIBLE);
        radioGroup.check(id);//默认准入条件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                id = checkedId;
                setListData();
            }
        });
        isDraw.setChecked(true);
        isDraw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    radioButton2.setVisibility(View.VISIBLE);
                } else {
                    radioButton2.setVisibility(View.GONE);
                }
            }
        });
//        List<BDataDictionaryEntity> projectType = DBUtils.getBDataDictionaryEntities("progect_type");
        projectType = session.getBDataDictionaryEntityDao().queryBuilder().where(BDataDictionaryEntityDao.Properties.DCode.eq("progect_type")).list();
        projectTypeSpinnerAdapter = new SpinnerAdapter<>(context, projectType, spinner).setListener(new ResponseListener() {
            @Override
            public void response(Object... data) {
                BDataDictionaryEntity b = (BDataDictionaryEntity) data[1];
                if (b.getDKey().equals("100")) {
                    isDraw.setVisibility(View.VISIBLE);
                    if (isDraw.isChecked()) {
                        radioButton2.setVisibility(View.VISIBLE);
                    } else {
                        radioButton2.setVisibility(View.GONE);
                    }
                } else {
                    radioButton2.setVisibility(View.GONE);
                    if (id == R.id.radioButton2) {
                        radioGroup.check(R.id.radioButton3);
                    }
                    isDraw.setVisibility(View.GONE);
                }
            }
        });
        spinner.setAdapter(projectTypeSpinnerAdapter);
        categoryTypes = session.getBDataDictionaryEntityDao().queryBuilder().where(BDataDictionaryEntityDao.Properties.DCode.eq("category_type")).list();
        workTypeSpinnerAdapter = new SpinnerAdapter<>(context, categoryTypes, spinner2);
        spinner2.setAdapter(workTypeSpinnerAdapter);
        listView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        listView.setAdapter(superAdapter = new SuperAdapter<String>(R.layout.content_createproject) {
            @Override
            public void bindView(ViewHolder viewHolder, String s, final int i) {
                ((TextView) viewHolder.getView(R.id.content)).setText(s);
                viewHolder.getView(R.id.layout).setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        new NoticeDialog().setMsg("是否删除该项？").setTitle("删除").setCancelButton("取消", null).setConfirmButton("删除", new ClickListener() {
                            @Override
                            public void click() {
                                deleteListData(i);
                            }
                        }).show(getFragmentManager(), "");
                        return false;
                    }
                });
            }
        });
        superAdapter.setData(datas);
        superAdapter.setEmptyDataView(R.layout.view_empty);
        setUserText();

    }

    private void initDefultData() {
        if (update) {//修改时除了基础信息，其他信息操作的时候就要修改，基础信息最后修改
            apBaseEntity = session.getEPBaseEntityDao().load((String) SPUtils.get(context, "project_ys_guid", ""));
            isDraw.setChecked(apBaseEntity.getIsDraw().equals("是"));
            isDraw.setEnabled(false);
            String guid = apBaseEntity.getGuid();//guid
            projectName.setText(apBaseEntity.getPBName());//设置项目名称
            List<String> queryList = new ArrayList<>();
            queryList.addAll(Arrays.asList(apBaseEntity.getPBCollectid().split(",")));
            queryList.remove(LoginInfo.getInfo(context).getUserId() + "");//去掉自己的ID，避免重复
            userEntities.clear();
            userEntities.addAll(session.getSysUserEntityDao().queryBuilder().where(SysUserEntityDao.Properties.UserId.in(queryList)).list());//设置参与人
            int i = 0;
            for (BDataDictionaryEntity b : projectType) {//设置项目类型
                if (b.getDKey().equals(apBaseEntity.getPBType())) {
                    spinner.setSelection(i);
                    break;
                }
                i++;
            }
            i = 0;
            for (BDataDictionaryEntity b : categoryTypes) {//设置改造类型
                if (b.getDKey().equals(apBaseEntity.getPBCategory())) {
                    spinner2.setSelection(i);
                    break;
                }
                i++;
            }
            spinner.setEnabled(false);//项目类型不能修改
            lineNames.clear();
            lineNames.addAll(DBUtils.getYsLineNames(guid));//线路台区
            materialEntities.clear();
            materialEntities.addAll(DBUtils.getYsMaterialEntities(guid));//导线型号
            setListData();
            setUserText();
        }
    }

    /**
     * 设置显示数据信息
     */
    private void setListData() {
        datas.clear();
        switch (id) {
            case R.id.radioButton2://导线
                datas.addAll(DataUtils.material2String(materialEntities));
                break;
            case R.id.radioButton3://台区
                datas.addAll(DataUtils.lineName2String(lineNames));
                break;
        }
        superAdapter.notifyDataSetChanged();
    }

    /**
     * 删除显示数据信息
     */
    private void deleteListData(int i) {
        switch (id) {
            case R.id.radioButton2://导线
                if (update) {
                    showMsg("导线不能删除");
                    return;
                }
                materialEntities.remove(i);
                break;
            case R.id.radioButton3://台区
                if (update) {
                    showMsg("台区不能删除");
                    return;
                }
                lineNames.remove(i);
                break;
        }
        setListData();
    }

    private Map<Integer, Boolean> map = new HashMap<>();//记录被勾选项,防止数据错乱

    @OnClick({R.id.user, R.id.add_button, R.id.right_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user:
                new ListCheckDialog<SysUserEntity>().setTitle("参与人员").setDatas(GreenDaoManager.getInstance().getmDaoSession().getSysUserEntityDao()
                        .queryBuilder().where(SysUserEntityDao.Properties.UserId.notEq(LoginInfo.getInfo(context).getUserId())).list()).setChecked(map).setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        userEntities.clear();
                        userEntities.addAll((List<SysUserEntity>) data[0]);
                        setUserText();
                        map = (Map<Integer, Boolean>) data[1];
                    }
                }).show(getFragmentManager(), "");
                break;
            case R.id.add_button:
                switch (id) {
                    case R.id.radioButton2:
                        new WireDialog().setEntities(materialEntities).setListener(new ResponseListener() {
                            @Override
                            public void response(Object... data) {
                                materialEntities.addAll((List<BMaterialEntity>) data[0]);
                                if (update) {
                                    saveWire(apBaseEntity.getGuid(), (List<BMaterialEntity>) data[0]);
                                }
                                setListData();
                            }
                        }).show(getFragmentManager(), "");
                        break;
                    case R.id.radioButton3:
                        new LineNameDialog().setListener(new ResponseListener() {
                            @Override
                            public void response(Object... data) {
                                lineNames.add((LineName) data[0]);
                                if (update) {
                                    List<LineName> line = new ArrayList<LineName>();
                                    line.add((LineName) data[0]);
                                    saveLineName(apBaseEntity.getGuid(), line);
                                }
                                setListData();
                            }
                        }).show(getFragmentManager(), "");
                        break;
                }
                break;
            case R.id.right_save:
                saveProject();
                break;
        }
    }

    private void setUserText() {
        String txt = LoginInfo.getInfo(context).getUsername();//默认就有
        for (SysUserEntity s : userEntities) {
            txt += "," + s.getUsername();
        }
        user.setText(txt);
    }

    /**
     * 保存项目基本信息
     */
    void saveProject() {
        String name = getText(projectName);
        if (!TestingUtils.isEmpty(context, name, "项目名称")) return;
        boolean isD = isDraw.isChecked();
        if (update) {//修改
            apBaseEntity.setPBName(name);
            apBaseEntity.setPBCategory(workTypeSpinnerAdapter.getSelectedItem().getDKey());//设置业务类型
            String collectId = LoginInfo.getInfo(context).getUserId() + "";//修改参与人员
            for (SysUserEntity s : userEntities) {
                collectId += "," + s.getUserId();
            }
            apBaseEntity.setPBCollectid(collectId);
            apBaseEntity.setPBDatastate("修改");
            session.getEPBaseEntityDao().update(apBaseEntity);
            T.showLong(context, "修改成功");
            finish();
        } else {//新增F
            if (isD && materialEntities.size() == 0 && projectTypeSpinnerAdapter.getSelectedItem().getDKey().equals("100")) {
                showMsg("导线型号不能为空");
                return;
            }
            if (lineNames.size() == 0) {
                showMsg("线路台区不能为空");
                return;
            }
            EPBaseEntity entity = new EPBaseEntity();
            entity.setGuid(UUID.randomUUID().toString());
            entity.setPBCategory(workTypeSpinnerAdapter.getSelectedItem().getDKey());//设置业务类型
            entity.setPBType(projectTypeSpinnerAdapter.getSelectedItem().getDKey());
            entity.setPBHive("10");
            entity.setPBState("10");
            entity.setPBName(name);
            entity.setIsDraw(isD ? "是" : "否");
            entity.setPBOrgid(LoginInfo.getInfo(context).getDeptId());
            String dKey = projectTypeSpinnerAdapter.getSelectedItem().getDKey();//获取项目类型数据字典
            BProjectApplicationEntity applicationEntity = DBUtils.getBProjectApplicationEntity(dKey);//获取申请书
            entity.setAGuid(applicationEntity.getGuid());
            List<BEstimateEntity> estimateEntities = DBUtils.getBEstimateEntities(dKey);
            String sGuid = "";
            for (BEstimateEntity s : estimateEntities) {
                if (sGuid.contains(s.getBGuid())) {//如果已经存在则不加入
                    continue;
                }
                if (!sGuid.equals("")) {
                    sGuid += ",";
                }
                sGuid += s.getBGuid();
            }
            entity.setSGuid(sGuid);
            String collectId = LoginInfo.getInfo(context).getUserId() + "";
            for (SysUserEntity s : userEntities) {
                collectId += "," + s.getUserId();
            }
            entity.setPBCollectid(collectId);
            entity.setPBAddtime(new Date());
            entity.setPBBookname(applicationEntity.getPAName());
            entity.setPBDatastate("新增");
            session.getEPBaseEntityDao().insert(entity);
            saveWire(entity.getGuid(), materialEntities);
            saveLineName(entity.getGuid(), lineNames);
            T.showLong(context, "创建成功");
            SPUtils.put(context, "project_ys_guid", entity.getGuid());
            finish();
        }
    }


    /**
     * 保存导线
     *
     * @param guid
     */
    void saveWire(String guid, List<BMaterialEntity> materialEntities) {
        for (BMaterialEntity b : materialEntities) {
            EPWireEntity a = new EPWireEntity();
            a.setGuid(UUID.randomUUID().toString());
            a.setPGuid(guid);
            a.setPMGuid(b.getGuid());
            a.setPWName(b.getMName());
            a.setPWDatastate("新增");
            session.getEPWireEntityDao().insertOrReplace(a);
        }
    }

    /**
     * 保存线路台区
     *
     * @param guid
     */
    void saveLineName(String guid, List<LineName> lineNames) {
        for (LineName b : lineNames) {
            EPRangeEntity a = new EPRangeEntity();
            a.setGuid(UUID.randomUUID().toString());
            a.setPGuid(guid);
            a.setPRDatastate("新增");
            a.setPRName(b.getName());
            a.setPRType(b.getpRType());
            a.setPRVoltage(b.getpRVoltage());
            session.getEPRangeEntityDao().insert(a);
        }
    }

}
